package com.yzw.monitororevent;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author: YangZhenWei
 * @PROJECT_NAME: nettyTeach
 * @DESCRIPTION: 客户端启动类,测试netty的超时机制 读超时，写超时，读写超时，以及心跳机制，在 handler 中实现 userEventTriggered方法
 * @USER: root
 * @DATE: 2023/2/8 22:51
 **/
public class AppClientReconnHeart {

    private final String host;
    private final int port;

    public AppClientReconnHeart(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();// io线程池
        try {
            Bootstrap bs = new Bootstrap();
            bs.group(group)
                    .channel(NioSocketChannel.class) // 实例化一个通道
                    .remoteAddress(new InetSocketAddress(host, port)) // 指定远程的ip和端口
                    .handler(new ChannelInitializer<SocketChannel>() {// 进行通道的初始化配置
                        /**
                         * 初始化通道，添加通道的处理handler
                         *
                         * @param socketChannel 通道
                         * @throws Exception
                         */
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 添加读写超时的handle
                            socketChannel.pipeline().addLast(new IdleStateHandler(5,0,0, TimeUnit.SECONDS));
                            socketChannel.pipeline().addLast(new HandlerClientReconnHeart());// 添加自定义的handler
                        }
                    });
            //链接获取异步操作的结果值，链接到远程节点，等待链接完成
            ChannelFuture future = bs.connect().sync();

            // 消息到服务器端，编码格式为utf-8
            // 每隔6秒向服务器发送一条消息
            while (true){
                Thread.sleep(3000);
                // 检测到读超时时，就向服务器发送一个消息包
                SimpleDateFormat dateFormat = new SimpleDateFormat("HH:MM:ss:SSS");
                String strDate = dateFormat.format(new Date());
                future.channel().writeAndFlush(Unpooled.copiedBuffer(strDate,CharsetUtil.UTF_8));
            }
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        new AppClientReconnHeart("127.0.0.1",18080).run();
    }
}
